package com.ruoyi.web.controller.commission;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.ruoyi.attached.domain.Attached;
import com.ruoyi.attached.service.IAttachedService;
import com.ruoyi.attachedData.service.IAttachedDataService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.report.domain.Report;
import com.ruoyi.report.service.IReportService;
import com.ruoyi.sample.domain.Sample;
import com.ruoyi.sample.service.ISampleService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import com.ruoyi.task.domain.Task;
import com.ruoyi.web.controller.system.SysUserController;
import com.ruoyi.web.controller.task.TaskController;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.commission.domain.Commission;
import com.ruoyi.commission.service.ICommissionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 委托Controller
 *
 * @author ruoyi
 * @date 2025-05-08
 */
@RestController
@RequestMapping("/commission/commission")
public class CommissionController extends BaseController
{
    @Autowired
    private ICommissionService commissionService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISampleService sampleService;

    @Autowired
    private IAttachedService attachedService;

    @Autowired
    private IReportService reportService;

    @Autowired
    private IAttachedDataService attachedDataService;

    @Resource
    private TaskController taskController;

    @Resource
    private SysUserServiceImpl sysUserService;


    /**
     * 查询委托列表(所有)
     */

    @GetMapping("/listAll")
    public AjaxResult listAll(Commission commission)
    {
        List<Commission> list = commissionService.selectCommissionList(commission);
        return AjaxResult.success(list);
    }

    /**
     * 查询委托列表
     */
    @PreAuthorize("@ss.hasPermi('commission:commission:list')")
    @GetMapping("/list")
    public TableDataInfo list(Commission commission)
    {
        startPage();
        List<Commission> list = commissionService.selectCommissionList(commission);

        return getDataTable(list);
    }

    /**
     * 导出委托列表
     */
    @PreAuthorize("@ss.hasPermi('commission:commission:export')")
    @Log(title = "委托", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Commission commission)
    {
        List<Commission> list = commissionService.selectCommissionList(commission);
        ExcelUtil<Commission> util = new ExcelUtil<Commission>(Commission.class);
        return util.exportExcel(list, "委托数据");
    }

    /**
     * 获取委托详细信息
     */
    @PreAuthorize("@ss.hasPermi('commission:commission:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(commissionService.selectCommissionById(id));
    }

    /**
     * 新增委托
     */
    @PreAuthorize("@ss.hasPermi('commission:commission:add')")
    @Log(title = "委托", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Commission commission) throws ParseException {
        String gc_commission_code=configService.selectConfigByKey("gc_commission_code");
        commission.setTableCode(gc_commission_code);

        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR); // 获取当前年份
        int month = calendar.get(Calendar.MONTH) + 1; // 获取当前月份（需要加1，因为月份从0开始）
        commissionService.insertCommission(commission);
        Long id = commission.getId();
        String number = "WT"+year+"-"+month+id;
        Commission commission2 = new Commission();
        commission2.setId(id);
        commission2.setNumber(number);
        commissionService.updateCommission(commission2);

        Commission commissionOne = commissionService.selectCommissionById(id);

        Task task = new Task();
        task.setCommissionId(commissionOne.getId());
        task.setEngineeringId(commissionOne.getEngineeringId());
        task.setTaskType("1");
        task.setStatus("0");
        task.setTaskContent(commissionOne.getEnterpriseName() + "对" + commissionOne.getEngineeringName()
                + "的委托单" + commissionOne.getNumber());
        SysUser sysUser = new SysUser();
        sysUser.setRoleId(3L);
        sysUser.setDeptId(100L);
        List<SysUser> sysUserList = sysUserService.selectUserList(sysUser);
        if(sysUserList.size() > 1){
            task.setChargePerson(sysUserList.get(0).getUserId().toString());
        }
        taskController.add(task);
        return AjaxResult.success(commissionOne);
    }

    /**
     * 修改委托
     */
    @PreAuthorize("@ss.hasPermi('commission:commission:edit')")
    @Log(title = "委托", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Commission commission)
    {
        commission.setUpdateType(DicConstants.BUSINESS_Manager.getCode());
//        commissionService.createExcel(commission.getId(),"D:/file/weituomuban.xlsx","D:/file/weituomuban222.xlsx");
        return toAjax(commissionService.updateCommission(commission));
    }

    /**
     * 删除委托
     */
    @PreAuthorize("@ss.hasPermi('commission:commission:remove')")
    @Log(title = "委托", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(commissionService.logicDeleteCommission(ids,DicConstants.BUSINESS_Manager.getCode(),SecurityUtils.getUserId()));
    }


    /**
     * 修改受理
     */
    @PreAuthorize("@ss.hasPermi('commission:commission:acceptance')")
    @Log(title = "委托", businessType = BusinessType.UPDATE)
    @PostMapping("/acceptance")
    public AjaxResult acceptance(@RequestBody Commission commission) throws ParseException {
        commission.setStatus("souli");
        //改变试验表的状态
        Commission commissionOne = commissionService.selectCommissionById(commission.getId());
        if("shinei".equals( commissionOne.getBusinessType() ) ){
            sampleService.updateSampleForStatus(commission.getId());
        }
        if("shiwai".equals( commissionOne.getBusinessType() ) ){
            attachedDataService.updateAttachedDataForStatus(commission.getId());
        }

        Task task = new Task();
        task.setCommissionId(commissionOne.getId());
        task.setEngineeringId(commissionOne.getEngineeringId());
        task.setTaskType("2");
        task.setStatus("0");
        task.setTaskContent( commissionOne.getEngineeringName() + "的委托单" + commissionOne.getNumber() +
                "已受理，请及时检测。");
        task.setChargePerson(commission.getBusinessManagerId().toString());
        taskController.add(task);

        LoginUser loginUser = getLoginUser();
        Task task1 = new Task();

//        task1.setChargePerson(loginUser.getUserId().toString());
        task1.setTaskType("1");
        task1.setCommissionId(commissionOne.getId());
        List<Task> taskList = taskController.listAll(task1);

        task1.setId(taskList.get(0).getId());
        task1.setStatus("1");
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String  date = sdf.format(new Date());
        task1.setExecuteTime(sdf.parse(date));
        taskController.edit(task1);

        int is_res = commissionService.updateCommission(commission);

        Map desc = commissionService.getInputPathAndOutputPath();
        String inputPath = desc.get("inputPath").toString();
        String outputPath = desc.get("outputPath").toString();
        String savePath = desc.get("savePath").toString();

        commissionService.createExcel(commission.getId(),inputPath,outputPath,savePath);

        return toAjax(is_res);
    }


    //字段回显内容
    @PostMapping("/getDetectionContentChange")
    public AjaxResult getDetectionContentChange(Long commissionId,String businessType )
    {
        //获取detection_content字段回显
        Map comm_map =  commissionService.getDetectionContent(commissionId,businessType);
        return AjaxResult.success(comm_map);
    }

    //废弃
    @PostMapping("/getAttachedInfo")
    public AjaxResult getAttachedInfo(String ids,String businessType )
    {
        Map attachedMap =  attachedService.getInfoAll(ids,businessType);
        return AjaxResult.success(attachedMap);
    }


    @PostMapping("/daoru")
    public AjaxResult daoru(Long commissionId) throws IOException {
        //commissionService.createExcel(commissionId,"D:/file/weituomuban.xlsx","D:/file/weituomuban222.xlsx");
        return AjaxResult.success("dddd");
    }



}
